const { Sequelize } = require('sequelize');

// 数据库配置
const sequelize = new Sequelize('lingxi_system', 'root', '888mei525', {
  host: 'localhost',
  dialect: 'mysql',
  timezone: '+08:00',
  logging: false
});

async function seedSalesOrders() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 检查是否已有销售订单数据
    const [countResult] = await sequelize.query('SELECT COUNT(*) as count FROM sales_orders');
    console.log(`销售订单表当前记录数: ${countResult[0].count}`);
    
    // 如果没有销售订单数据，则创建一些示例订单
    if (countResult[0].count === 0) {
      console.log('正在创建示例销售订单数据...');
      
      const orders = [];
      const orderStatuses = ['pending', 'paid', 'shipped', 'completed', 'cancelled'];
      const invoiceStatuses = ['uninvoiced', 'invoiced', 'sent'];
      const collectionStatuses = ['pending', 'contacted', 'promised', 'paid', 'difficult'];
      const platformSources = ['zcy', 'manual'];
      
      for (let i = 1; i <= 20; i++) {
        const order = {
          order_no: `SO20231108${String(i).padStart(4, '0')}`,
          platform_order_id: `ZCY20231108${String(i).padStart(4, '0')}`,
          customer_id: (i % 5) + 1, // 假设有5个客户
          order_amount: (Math.floor(Math.random() * 100000) + 1000).toFixed(2),
          order_status: orderStatuses[Math.floor(Math.random() * orderStatuses.length)],
          order_date: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' '),
          platform_source: platformSources[Math.floor(Math.random() * platformSources.length)],
          invoice_status: invoiceStatuses[Math.floor(Math.random() * invoiceStatuses.length)],
          invoice_date: new Date(Date.now() - Math.floor(Math.random() * 20) * 24 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' '),
          responsible_salesman: `销售${String.fromCharCode(65 + (i % 5))}`,
          invoice_number: `INV20231108${String(i).padStart(4, '0')}`,
          collection_status: collectionStatuses[Math.floor(Math.random() * collectionStatuses.length)],
          collection_count: Math.floor(Math.random() * 5),
          last_collection_date: new Date(Date.now() - Math.floor(Math.random() * 10) * 24 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' '),
          last_collection_result: `催款结果${i}`,
          next_followup_date: new Date(Date.now() + Math.floor(Math.random() * 10) * 24 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' '),
          created_at: new Date().toISOString().slice(0, 19).replace('T', ' '),
          updated_at: new Date().toISOString().slice(0, 19).replace('T', ' '),
          organization_id: 1,
          is_gift: Math.random() > 0.5 ? 1 : 0
        };
        
        orders.push(order);
      }
      
      // 插入数据到数据库
      for (const order of orders) {
        try {
          const query = `
            INSERT INTO sales_orders (
              order_no, platform_order_id, customer_id, order_amount, order_status, order_date,
              platform_source, invoice_status, invoice_date, responsible_salesman,
              invoice_number, collection_status, collection_count, last_collection_date,
              last_collection_result, next_followup_date, created_at, updated_at, organization_id, is_gift
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
          `;
          
          const values = [
            order.order_no, order.platform_order_id, order.customer_id, order.order_amount, order.order_status, order.order_date,
            order.platform_source, order.invoice_status, order.invoice_date, order.responsible_salesman,
            order.invoice_number, order.collection_status, order.collection_count, order.last_collection_date,
            order.last_collection_result, order.next_followup_date, order.created_at, order.updated_at, order.organization_id, order.is_gift
          ];
          
          await sequelize.query(query, {
            replacements: values,
            type: Sequelize.QueryTypes.INSERT
          });
          
          console.log(`成功插入订单: ${order.order_no}`);
        } catch (insertError) {
          console.error(`插入订单 ${order.order_no} 时出错:`, insertError.message);
        }
      }
      
      console.log(`成功插入 ${orders.length} 条销售订单数据`);
    } else {
      console.log('销售订单表中已有数据，跳过数据填充');
    }
    
    // 验证数据插入
    const [finalCountResult] = await sequelize.query('SELECT COUNT(*) as count FROM sales_orders');
    console.log(`销售订单表最终记录数: ${finalCountResult[0].count}`);
    
    // 关闭连接
    await sequelize.close();
  } catch (error) {
    console.error('数据填充时出错:', error.message);
    console.error('错误堆栈:', error.stack);
  }
}

seedSalesOrders();